import { useMatches } from "@tanstack/react-router";
import { useMemo } from "react";

export interface ActivatedRoute {
	id: string;
	title?: string;
	url: string;
}

export const useActivatedRoute = () => {
	const matches = useMatches();

	const last = matches.at(-1);

	if (!last) {
		throw new Error("No matches found");
	}

	const activated = useMemo(
		() =>
			({
				id: last.id,
				url: last.fullPath,
				title: (last.meta?.find((x) => x?.title)?.title as string) || last.id,
			}) satisfies ActivatedRoute,
		[last.fullPath, last.id, last.meta],
	);

	console.log(`activated: ${activated.url}`);

	return activated;
};
